<?php
namespace app\common\model;

class Article extends BaseModel{

	protected static function init(){
		// 新增后
		Article::event('after_insert', function ($obj) {
			$article_id = $obj->data['article_id'];
			$content    = input('content');

			$data['article_id'] = $article_id;
			$data['content']    = self::setContent($content);
			db('ArticleContent')->insert($data);
		});
		// 更新后
		Article::event('after_update', function ($obj) {
			$article_id = input('article_id');
			$content    = input('content');
			$data['content'] = self::setContent($content);
			db('ArticleContent')->where(array('article_id' => $article_id))->update($data);
		});
	}
	/**
	 * 文章内容获取器
	 * @param  string $content [description]
	 * @param  array  $data    [description]
	 * @return [type]          [description]
	 */
	public function getContentAttr($content = '', $data = array()){
		$article_id = $data['article_id'];
		$content    = $content ? $content : db('ArticleContent')->where(array('article_id' => $article_id))->value('content');
		$content    = model('File')->html_file_url_oss($content);

		return $content;
	}
	/**
	 * 文章内容修改器
	 * @param string $content [description]
	 * @param array  $data    [description]
	 */
	public function setContent($content = '', $data = array()){
		$content = $content ? $content : $data['content'];
		$content = model('File')->html_osspath_local($content);

		return $content ? $content : '';
	}
	/**
	 * 获取更新后的查看数量
	 * @param  string $view_num [description]
	 * @param  array  $data     [description]
	 * @return [type]           [description]
	 */
	public function getUpdateViewNumAttr($view_num = '', $data = array()){
		$view_num   = $view_num ? $view_num : $data['view_num'];
		$article_id = $data['article_id'];
		$this->where(array('article_id' => $article_id))->setInc('view_num');

		return $view_num + 1;
	}
	// 封面URL获取器
	public function getCoverUrlAttr($cover_id = '', $data = array()){
		
		$cover_id = $cover_id ? $cover_id : $data['cover_id'];
		$img_url  = model('File')->get_path($cover_id);

		return $img_url ? $img_url : '';
	}
	// 用户收藏时间获取器
	public function getUserFavTimeAttr($article_id = 0, $data = []){
		$article_id = $article_id ? $article_id : $data['article_id'];
		$user_id    = $this->user_id();
		
		$where['user_id']   = $user_id;
		$where['fav_type']  = 'article_fav';
		$where['object_id'] = $article_id;
		$time = db('UserFav')->where($where)->value('create_time');

		return $time > 0 ? $time : 0;
	}
	/**
	 * 获取推荐清单
	 * @param  string  $module 模块名称
	 * @param  integer $limit  数量
	 */
	public function get_recommend_list($module = '', $limit = 10){
		$where['module']        = $module;
		$where['is_delete']     = 0;
		$where['status']        = 1;
		$where['recommend_num'] = ['gt', 0];
		$order = 'recommend_num desc,article_id desc';
		$list  = $this->where($where)->order($order)->limit($limit)->select();

		return $list;
	}

}